from PyQt5.QtWidgets import (QMainWindow, QTabWidget, QVBoxLayout, 
                            QHBoxLayout, QWidget, QPushButton, QComboBox)
from .console_widget import ConsoleWidget
from .settings_dialog import SettingsDialog

class MainWindow(QMainWindow):
    def __init__(self, serial_driver, data_processor):
        super().__init__()
        self.serial_driver = serial_driver
        self.data_processor = data_processor
        self.init_ui()
        self.connect_signals()

    def init_ui(self):
        """初始化UI"""
        self.setWindowTitle("PyQt 串口助手")
        self.setGeometry(100, 100, 800, 600)

        # 主布局
        central_widget = QWidget()
        self.setCentralWidget(central_widget)
        main_layout = QVBoxLayout(central_widget)

        # 工具栏
        toolbar_layout = QHBoxLayout()
        self.port_combo = QComboBox()
        self.refresh_btn = QPushButton("刷新")
        self.connect_btn = QPushButton("连接")
        self.settings_btn = QPushButton("设置")

        toolbar_layout.addWidget(self.port_combo)
        toolbar_layout.addWidget(self.refresh_btn)
        toolbar_layout.addWidget(self.connect_btn)
        toolbar_layout.addWidget(self.settings_btn)
        main_layout.addLayout(toolbar_layout)

        # 控制台
        self.console = ConsoleWidget()
        main_layout.addWidget(self.console)

        # 状态栏
        self.statusBar().showMessage("就绪")

    def connect_signals(self):
        """连接信号与槽"""
        self.refresh_btn.clicked.connect(self.refresh_ports)
        self.connect_btn.clicked.connect(self.toggle_connection)
        self.settings_btn.clicked.connect(self.show_settings)
        self.serial_driver.data_received.connect(self.data_processor.process)
        self.data_processor.data_updated.connect(self.console.append_data)
        self.serial_driver.connection_status.connect(self.update_connection_status)

    def refresh_ports(self):
        """刷新串口列表"""
        self.port_combo.clear()
        self.port_combo.addItems(self.serial_driver.list_ports())

    def toggle_connection(self):
        """切换连接状态"""
        if self.serial_driver.serial_port and self.serial_driver.serial_port.is_open:
            self.serial_driver.close()
        else:
            port = self.port_combo.currentText()
            if port:
                self.serial_driver.open(port)

    def update_connection_status(self, connected):
        """更新连接状态显示"""
        if connected:
            self.connect_btn.setText("断开")
            self.statusBar().showMessage(f"已连接到 {self.port_combo.currentText()}")
        else:
            self.connect_btn.setText("连接")
            self.statusBar().showMessage("未连接")

    def show_settings(self):
        """显示设置对话框"""
        dialog = SettingsDialog(self)
        dialog.exec_()